package com.cennavi.minemap.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;

import com.cennavi.minemap.bean.LogBean;

@Component
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
public class LogDao extends AbstractDao {

	private List<LogBean> logBeanList = new ArrayList<>();
	
	public int insert(final LogBean logBean) {
		jdbcTemplate.setDataSource(pgDataSource);
		
		final String sql = "INSERT INTO MM_TILE_LOG (tokenid, soluid, source, ip, datetime, userid) " + "VALUES(?, ?, ?, ?, ?, ?)";
		KeyHolder keyHolder = new GeneratedKeyHolder();
		
		jdbcTemplate.update(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
				PreparedStatement ps = conn.prepareStatement(sql,
						new String[] { "id" });
				ps.setString(1, logBean.getToken_id());
				ps.setInt(2, logBean.getSolu_id());
				ps.setString(3, logBean.getDatasource());
				ps.setString(4, logBean.getIp());
				ps.setString(5, logBean.getDatetime());
				ps.setInt(6, logBean.getUser_id());
				return ps;
			}
		}, keyHolder);
		
		
	
		return keyHolder.getKey().intValue();
	}
	
	public void insert(final List<LogBean> list){
		jdbcTemplate.setDataSource(pgDataSource);
		final String sql = "INSERT INTO MM_TILE_LOG (tokenid, soluid, source, ip, datetime, userid) " + "VALUES(?, ?, ?, ?, ?, ?)";
		
		jdbcTemplate.batchUpdate(sql,new BatchPreparedStatementSetter() {
			
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				// TODO Auto-generated method stub
				ps.setString(1, list.get(i).getToken_id());
				ps.setInt(2, list.get(i).getSolu_id());
				ps.setString(3, list.get(i).getDatasource());
				ps.setString(4, list.get(i).getIp());
				ps.setString(5, list.get(i).getDatetime());
				ps.setInt(6, list.get(i).getUser_id());
			}
			
			@Override
			public int getBatchSize() {
				// TODO Auto-generated method stub
				return list.size();
			}
		});
	}

	public synchronized void addLogBean(LogBean logBean){
		if (logBeanList.size() >= 1000){
			insert(logBeanList);
			logBeanList.clear();
			logBeanList.add(logBean);
		}else{
			logBeanList.add(logBean);
		}
	}
}
